//
// Created by liushuai on 2021/1/5.
//

#include "addTwoNumbers.h"
int linkLength(ListNode* head){
    int length = 0;
    ListNode* current = head;
    if(!current)
        return length;
    while(current){
        current = current->next;
        length++;
    }
    return length;
}

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2){
    if(!l1)
        return l2;
    if(!l2)
        return l1;
    ListNode* head1 = l1;
    ListNode* head2 = l2;
    int list_length1 = linkLength(head1);
    int list_length2 = linkLength(head2);
    int min_length = list_length1<list_length2?list_length1:list_length2;
    int hight = 0;
    ListNode* result_head = nullptr;
    ListNode* current_node = nullptr;
    for(int node=0;node<min_length;node++){

        int value = head2->val+head1->val+hight;
        hight = value/10;
        int elem = value%10;
        if(node == 0){
            result_head = new ListNode(elem);
            head1 = head1->next;
            head2 = head2->next;
            if(!current_node)
                current_node = result_head;
            continue;
        }


        ListNode* op_node = new ListNode(elem);
        current_node->next = op_node;
        current_node = op_node;
        head1 = head1->next;
        head2 = head2->next;
    }
    while  (head1){
        int value = (head1->val+hight);
        hight = value/10;
        head1->val = value%10;
        current_node->next = head1;
        current_node=head1;
        head1=head1->next;
    }

    while (head2){
        int value = (head2->val+hight);
        hight = value/10;
        head2->val = value%10;
        current_node->next = head2;
        current_node=head2;
        head2=head2->next;
    }
    if(hight)
        current_node->next = new ListNode(1);
    return result_head;

}